package com.gcxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.entity.Project;
import com.gcxy.entity.Semester;
import com.gcxy.entity.UserProject;
import com.gcxy.mapper.UserProjectMapper;
import com.gcxy.service.ProjectService;
import com.gcxy.service.SemesterService;
import com.gcxy.service.UserProjectService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * Copyright (C), 2024-2024, BUG闭退！
 * Author: Huang先森
 * Date: 2024/8/12 17:39
 * FileName: UserProjectServiceImpl
 * Description:
 */
@Service
public class UserProjectServiceImpl extends ServiceImpl<UserProjectMapper, UserProject> implements UserProjectService {

    @Resource
    private ProjectService projectService;

    @Resource
    private SemesterService semesterService;

    @Override
    public void insertStudentProject(List<String> projectList, Integer studentId, Integer semesterId) {
        // 绑定学期
        Semester semester = semesterService.getCurrentSemester();
        if (projectList != null && !projectList.isEmpty()) {
            for (String projectName : projectList) {
                UserProject userProject = new UserProject();
                userProject.setProjectId(projectService.getByProjectName(projectName).getId());
                userProject.setUserId(studentId);
                if (semester == null) {
                    if (ObjectUtils.isEmpty(semester)) {
                        throw new RuntimeException("学期绑定失败，学期中未创建新的学期!");
                    } else {
                        userProject.setSemesterId(semester.getId());
                    }
                } else {
                    userProject.setSemesterId(semesterId);
                }
                boolean result = save(userProject);
                if (!result){
                    throw new RuntimeException("插入学生项目关系失败！");
                }
            }
        }
    }

    /**
     * 获取当前学期学生所选项目
     *
     * @param studentId
     * @param semesterId
     * @return
     */
    @Override
    public List<UserProject> getStudentProjectList(Integer studentId, Integer semesterId) {
        LambdaQueryWrapper<UserProject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserProject::getUserId, studentId)
                .eq(UserProject::getSemesterId, semesterId);
        return list(wrapper);
    }
}
